<template>
  <div v-loading="$store.state.app.loading" class="goods-tabs">
    <div class="app-container">
      <!-- 筛选部分 -->
      <div class="app-container-hd" style="display: flex;flex-direction: column;overflow-y: scroll;">
        <div class="toolbar-search" style="margin-bottom: -10px;">
          <el-form ref="importParams" class="search-form" :model="importParams" :inline="true" size="mini">

            <div class="form-button">
              <el-form-item>
                <el-upload
                  action=""
                  :show-file-list="false"
                  :http-request="handleImport"
                  accept=".xlsx"
                >
                  <el-button type="primary">导入数据</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-upload
                  action=""
                  :show-file-list="false"
                  :http-request="handleImportWithImage"
                  accept=".xlsx"
                >
                  <el-button type="primary">导入带图数据</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-refresh" type="primary" @click="handleSearch">刷新</el-button>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-download" size="mini" type="success" @click="handleDownloadExcel">下载导入模板</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <!-- 表格部分 -->
        <div v-loading="$store.state.app.loading" class="table-main" style="flex-grow: 1;">
          <el-table
            ref="multipleTable"
            highlight-current-row
            :data="listData"
            :border="true"
            :empty-text="$store.state.app.loading ? '正在加载数据' : null"
          >
            <el-table-column prop="created_at" label="导入时间" width="200" align="center" />

            <el-table-column prop="label_price" label="执行类型" width="120" align="center">
              <span>导表入库</span>
            </el-table-column>

            <el-table-column prop="name" label="表格名称" align="center" />

            <el-table-column prop="result" label="执行结果" align="center">
              <template slot-scope="item">
                <div>
                  导入{{ item.row.success_total + item.row.failure_total }}条，
                  <span class="color-success">执行成功{{ item.row.success_total }}条，</span>
                  <span class="color-danger">执行失败{{ item.row.failure_total }}条</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="状态" width="120" align="center">
              <template slot-scope="item">
                <div v-if="item.row.status === 1">执行完成</div>
                <div v-else class="color-primary">执行中</div>
              </template>
            </el-table-column>

            <el-table-column prop="action" label="操作" width="120" align="center">
              <template slot-scope="item">
                <div class="color-primary" style="cursor: pointer;" @click="handleShowLog(item.row)">查看失败结果</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="app-container-ft">
        <paginate :total="searchParams.total" :per-page="searchParams.per_page" :page="searchParams.page" @paginate-change="handleSearch" />
      </div>
    </div>

    <import-log
      v-if="logModal"
      :title="logTitle"
      :file-id="logFileId"
      @on-cancel-modal="handleCancelModal"
    />
  </div>
</template>

<script>
import Paginate from '@/components/Paginate/index'
import { importGoods, getImportFile } from '@/api/goodsImport'
import { mapGetters } from 'vuex'
import importLog from './components/importLog'

export default {
  components: { Paginate, importLog },
  data() {
    return {
      initial: true,
      mode: 1,
      listData: [],

      logModal: false,
      logTitle: null,
      logFileId: null,

      stockMode: 0,
      importParams: {},

      searchParams: {
        total: null,
        page: null,
        per_page: parseInt(process.env.VUE_APP_PER_PAGE)
      }
    }
  },
  computed: {
    ...mapGetters(['merchant']),
    canImport() {
      return this.importParams.retainer_id
    }
  },
  mounted() {
    // 初始化方法
    this.initialize()
  },
  methods: {
    // 初始化数据列表
    initialize() {
      // 获取数据列表
      this.$store.commit('app/SET_LOADING', true)
      getImportFile({
        ...this.searchParams
      }).then(res => {
        if (res !== false) {
          this.listData = res.data
          this.searchParams.total = Number(res['total'])
          this.searchParams.page = Number(res['current_page'])
          this.searchParams.per_page = Number(res['per_page'])
        }
        this.$nextTick(function() {
          this.$store.commit('app/SET_LOADING', false)
        })
      })
    },
    // 根据条件筛选数据
    handleSearch(value, field) {
      // 重置表单数据
      if (field === 'reset') {
        this.searchParams.page = 1
        this.$refs[value].resetFields()
        // 页码参数变更
      } else if (field) {
        this.searchParams.page = 1
        this.searchParams[field] = value
      } else {
        this.searchParams.page = 1
      }
      this.initialize()
    },
    // 关闭数据编辑窗口
    handleCancelModal: function(method, refresh = false) {
      if (refresh === true) {
        this.initialize()
      }
      this[method] = false
    },
    handleImport(data) {
      if ((data.file.size / 1024 / 1024) > 100) {
        this.$message.warning('上传文件不能超过100MB'); return
      }
      this.$store.commit('app/SET_LOADING', true)
      const fd = new FormData()
      fd.append('file', data.file)
      // fd.append('mode', 'async')
      fd.append('mode', 'sync')
      importGoods(fd)
        .then(res => {
          this.handleSearch()
        })
        .catch(res => {
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        })
      return false
    },
    handleImportWithImage(data) {
      if ((data.file.size / 1024 / 1024) > 100) {
        this.$message.warning('上传文件不能超过100MB'); return
      }
      this.$store.commit('app/SET_LOADING', true)
      const fd = new FormData()
      fd.append('file', data.file)
      fd.append('image', 1)
      // fd.append('mode', 'async')
      fd.append('mode', 'sync')
      importGoods(fd)
        .then(res => {
          this.handleSearch()
        })
        .catch(res => {
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        })
      return false
    },
    handleShowLog(itemData) {
      if (itemData) {
        this.logTitle = itemData.name
        this.logFileId = itemData.file_id
        this.logModal = true
      }
    },
    handleClear() {
      this.$refs['importParams'].resetFields()
    },
    handleDownloadExcel(tag) {
      const a = document.createElement('a')
      a.href = process.env.VUE_APP_BASE_URL + '/excel/商品导入模板.xlsx'
      a.click()
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-tabs {
  height: 1%;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  .tabs {
    flex-grow: 0;
    background-color: #fff;
    margin: 10px 10px 1px 10px;
    padding: 15px 15px 5px 15px;
    .el-button.stuff {
      padding-left: 27px;
      padding-right: 27px;
    }
  }
  .app-container {
    flex-grow: 1;
    margin-top: 0;
    background-color: #fff;
  }
}
</style>
